package com.crrcdt.mail.receiver;

import com.crrcdt.mail.constant.MailConstants;
import com.crrcdt.mail.entity.Employee;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @作者 江南一点雨
 * @公众号 江南一点雨
 * @微信号 a_java_boy
 * @GitHub https://github.com/lenve
 * @博客 http://wangsong.blog.csdn.net
 * @网站 http://www.javaboy.org
 * @时间 2019-11-24 7:59
 */
@Component
public class MailReceiver {

    public static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    StringRedisTemplate redisTemplate;
    //TODO 接收消息q->c(监听队列)
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
//    message接收消息 channal当前传输数据的通道 @RabbitHandler 可以对接收到的消息进行重载处理，不同的消息不同的处理
//    现在是没有进行消息的重载处理
    public void handler(Message message, Channel channel) throws IOException {
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        // 手动ack  Long deliveryTag（派发的标签） = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //new CorrelationData(mailSendLog.getMsgId())【就是前面放进去的唯一id】
        String msgId = (String) headers.get("spring_returned_message_correlation");
//        String msgId = "a358e586-01b8-471c-8054-45459ba2a7cc";
        if (redisTemplate.opsForHash().entries("mail_log").containsKey(msgId)) {//如何保证 MQ 的消费是幂等性 redis
            //redis 中包含该 key，说明该消息已经被消费过
            logger.info(msgId + ":消息已经被消费");
            // 手动签收 channel.basicAck(deliveryTag, false);
            //TODO 消费端ack机制（默认客户端ack机制是不管你有没有消费完（消费完会ack 手动），默认自动确定ack,我只管发送给你了就行，这样会造成消息丢失，
            // 所以要手动ack）
            channel.basicAck(tag, false);//确认消息已消费
            return;
        }
        //收到消息，发送邮件
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            helper.setTo(employee.getEmail());
            helper.setFrom(mailProperties.getUsername());
            helper.setSubject("入职欢迎");
            helper.setSentDate(new Date());
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", "employee.getPosition().getName()");
            context.setVariable("joblevelName", "employee.getJobLevel().getName()");
            context.setVariable("departmentName", "employee.getDepartment().getName()");
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            javaMailSender.send(msg);
            redisTemplate.opsForHash().put("mail_log", msgId, "javaboy");
            channel.basicAck(tag, false);
            logger.info(msgId + ":邮件发送成功");
        } catch (MessagingException e) {
            channel.basicNack(tag, false, true);//异常 重新放到队列中，而不是丢失
            e.printStackTrace();
            logger.error("邮件发送失败：" + e.getMessage());
        }
    }
}
